//  导入路由脚本文件中的  asyncRoutes 是属性
import { asyncRoutes, constantRoutes } from "@/router";
//  导入获取菜单数据的方法
import { getMenuListApi } from "@/api/user";
import Layout from "@/layout";

/**
 * Use meta.role to determine if the current user has permission
 *  判断当前登录用户是否拥有角色下的菜单信息
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    // some 方法  循环数组里面的元素，返回true 直接终止
    return roles.some((role) => route.meta.roles.includes(role));
  } else {
    return true;
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
//   过滤出所拥有的菜单信息
export function filterAsyncRoutes(routes, roles) {
  const res = [];

  routes.forEach((route) => {
    const tmp = { ...route };
    // 判断是否拥有响应的权限
    if (hasPermission(roles, tmp)) {
      // 获取该路由对应组件
      let component = tmp.component;
      //   判断该路由是否有组件
      if (route.component) {
        //  判断是否有根组件
        if (component === "Layout") {
          tmp.component = Layout;
        } else {
          // 获取对应具体的组件信息
          tmp.component = (reslove) =>
            require([`@/views${component}`], reslove);
        }
      }

      // 如果有 子菜单
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles);
      }
      res.push(tmp);
    }
  });

  return res;
}

const state = {
  routes: [],
  addRoutes: [],
};

const mutations = {
  //  将路由信息保存到stroe
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes;
    state.routes = constantRoutes.concat(routes);
  },
};

const actions = {
  // 动态生成路由
  generateRoutes({ commit }, roles) {
    return new Promise((resolve, reject) => {
      getMenuListApi()
        .then((res) => {
          console.log("----------");
          // console.log(res.data);
          // console.log(asyncRoutes);
          //  存放对应权限的路由信息
          let accessedRoutes;
          // 判断状态码是否是200
          if (res.code == 200) {
            accessedRoutes = filterAsyncRoutes(res.data, roles);
          }
          // 将路由信息保存到vuex
          commit("SET_ROUTES", accessedRoutes);
          resolve(accessedRoutes);
        })
        .catch((err) => {
          reject(err);
        });

      // if (roles.includes("admin")) {
      //   accessedRoutes = asyncRoutes || [];
      // } else {
      //   accessedRoutes = filterAsyncRoutes(asyncRoutes, roles);
      // }
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
